<?php

namespace app\supplier\controller\page;

use app\common\enum\settings\SettingEnum;
use app\supplier\controller\Controller;
use app\supplier\model\page\Page as PageModel;
use app\supplier\model\page\PageCategory as PageCategoryModel;
use app\supplier\model\supplier\Region;
use app\shop\model\settings\Setting as SettingModel;
use app\supplier\model\supplier\Supplier;
use app\supplier\model\supplier\User as ProxyUser;

/**
 * App页面管理
 */
class Page extends Controller
{


    public function copyPage($level, $fromId, $page_type)
    {
        $supplier = (new Supplier())->find($this->getSupplierId());
        if (!$supplier || $supplier["is_recycle"] == 1 || $supplier["is_audit"] != 1) {
            return $this->renderError('商户不存在或异常');
        }

        $noAuth = Supplier::checkauth($this->getSupplierId(),'page');
        $model = new PageModel;
        if ($level == -1 && $fromId > 0) {
            $fromPage = $model->find($fromId);
            $page_name = '复制自-' . $fromId;
        } elseif ($level == 0) {
            $fromPage = $model->where(['is_delete' => 0, 'page_type' => $page_type, "proxy_id" => 0, "province_id" => 0, "city_id" => 0])
                ->order("is_default", "desc")
                ->find();
            $page_name = '复制自-平台页面';
        }
        if (empty($fromPage)) {
            return $this->renderError('源页面不存在');
        }
        $data = [
            'page_type' => $fromPage['page_type'],
            'page_name' => $page_name,
            'page_data' => $fromPage["page_data"],
            'is_default' => 0,
            'app_id' => $model::$app_id,
            'is_delete' => 0,
            'province_id' => $supplier["province_id"],
            'city_id' => $supplier["city_id"],
            'proxy_id' => $supplier["proxy_id"],
            'shop_supplier_id' => $this->getSupplierId(),
            'is_audit' => $noAuth?1:0,
        ];
        $model->save($data);
        return $this->renderSuccess('复制成功');
    }

    /**
     * 页面列表
     */
    public function list()
    {
        $model = new PageModel;
        $list = $model->getList($this->postData(), 10, $this->getSupplierId());
        //查找默认
        $default = $model::getHomeDefault($this->getSupplierId());
        return $this->renderSuccess('', compact('list', 'default'));
    }

    /**
     * 页面列表
     */
    public function index()
    {
        $model = new PageModel;
        $list = $model->getList($this->postData(), 20, $this->getSupplierId());
        return $this->renderSuccess('', compact('list'));
    }

    /**
     * 新增页面
     */
    public function add()
    {
        $model = new PageModel;
        if ($this->request->isGet()) {
            return $this->renderSuccess('', [
                'defaultData' => $model->getDefaultItems(),
                'jsonData' => ['page' => $model->getDefaultPage(), 'items' => []],
                'opts' => [
                    'catgory' => [],
                ]
            ]);
        }
        // 接收post数据
        $post = $this->postData();
        if (!$model->add(json_decode($post['params'], true), 20, $this->getSupplierId())) {
            return $this->renderError($model->getError() ?: '添加失败');
        }
        return $this->renderSuccess('添加成功');
    }

    /**
     * 首页编辑
     * @return \think\response\Json
     */
    public function home()
    {
        return $this->edit();
    }

    /**
     * 编辑页面
     */
    public function edit($page_id = null)
    {
        $model = $page_id > 0 ? PageModel::detail($page_id) : PageModel::getHomePage();
        if ($this->request->isGet()) {
            $jsonData = $model['page_data'];
            jsonRecursive($jsonData);
            return $this->renderSuccess('', [
                'defaultData' => $model->getDefaultItems(),
                'jsonData' => $jsonData,
                'opts' => [
                    'catgory' => [],
                ]
            ]);
        }

        // 接收post数据
        $post = $this->postData();
        if (!$model->edit(json_decode($post['params'], true), $this->getSupplierId())) {
            return $this->renderError($model->getError() ?: '更新失败');
        }
        return $this->renderSuccess('更新成功');
    }

    /**
     * 删除页面
     */
    public function delete($page_id)
    {
        // 帮助详情
        $model = PageModel::detail($page_id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    public function categoryList()
    {


        $list = [];
        $model = new PageCategoryModel;
        $where = ["proxy_id" => 0, "province_id" => 0, "city_id" => 0];
        $default = $model->where($where)->find();

        $where = ["shop_supplier_id" => $this->getSupplierId()];
        $category = $model->where($where)->find();
        if (empty($category)) {
            $category = clone $default;
        }
        $list[] = $category;
        return $this->renderSuccess('', compact('list'));
    }

    /**
     * 分类模板
     */
    public function category()
    {
        $post = $this->postData();

        $supplier = (new Supplier())->find($this->getSupplierId());
        if (!$supplier || $supplier["is_recycle"] == 1 || $supplier["is_audit"] != 1) {
            return $this->renderError('商户不存在或异常');
        }

        $where = ["shop_supplier_id" => $this->getSupplierId()];
        $model = new PageCategoryModel;
        $category = $model->where($where)->find();
        if ($this->request->isGet()) {
            if (empty($category)) {
                $where = ["proxy_id" => 0, "province_id" => 0, "city_id" => 0];
                $model = $model->where($where)->find();
            } else {
                $model = $category;
            }
            return $this->renderSuccess('', compact('model'));
        }
        $data["share_title"] = $post["share_title"];
        $data["category_style"] = $post["category_style"];
        $data["province_id"] = $supplier["province_id"];
        $data["city_id"] = $supplier["city_id"];
        $data["proxy_id"] = $supplier["proxy_id"];
        if ($category) {
            $category->save($data);
        } else {
            $data["shop_supplier_id"] = $this->getSupplierId();
            $data["is_audit"] = 1;
            $data["app_id"] = $model::$app_id;
            $model->newQuery()->save($data);
        }

        return $this->renderSuccess('更新成功', $model->getLastSql());
    }

    /**
     * 新增页面
     */
    public function addPage()
    {
        $model = new PageModel;
        if ($this->request->isGet()) {
            return $this->renderSuccess('', [
                'defaultData' => $model->getDefaultItems(),
                'jsonData' => ['page' => $model->getDefaultPage(), 'items' => []],
                'opts' => [
                    'catgory' => [],
                ]
            ]);
        }
        // 接收post数据
        $post = $this->postData();
        if (!$model->add(json_decode($post['params'], true), 10, $this->getSupplierId())) {
            return $this->renderError($model->getError() ?: '添加失败');
        }
        return $this->renderSuccess('添加成功');
    }

    /**
     * 编辑页面
     */
    public function editPage($page_id)
    {
        $model = PageModel::detail($page_id);
        if ($this->request->isGet()) {
            $jsonData = $model['page_data'];
            jsonRecursive($jsonData);
            return $this->renderSuccess('', [
                'defaultData' => $model->getDefaultItems(),
                'jsonData' => $jsonData,
                'opts' => [
                    'catgory' => [],
                ]
            ]);
        }
        // 接收post数据
        $post = $this->postData();
        if (!$model->edit(json_decode($post['params'], true), $this->getSupplierId())) {
            return $this->renderError($model->getError() ?: '更新失败');
        }
        return $this->renderSuccess('更新成功');
    }

    /**
     * 删除页面
     */
    public function deletePage($page_id)
    {
        // 详情
        $model = PageModel::detail($page_id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 设置默认
     */
    public function setPage($page_id)
    {
        // 页面详情
        $model = PageModel::detail($page_id);
        if (!$model->setDefault()) {
            return $this->renderError($model->getError() ?: '设置失败');
        }
        return $this->renderSuccess('设置成功');
    }

    /**
     * 商城设置
     */
    public function nav()
    {
        if ($this->request->isGet()) {
            $data = SettingModel::getItem('nav');
            return $this->renderSuccess('', compact('data'));
        }
        $model = new SettingModel;
        $data = $this->postData();
        if ($model->edit('nav', $data)) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

    /**
     * 底部菜单
     */
    public function bottomnav()
    {
        $vars = SettingModel::getItem(SettingEnum::NAV);
        return $this->renderSuccess('', compact('vars'));
    }

    /**
     * 底部菜单设置
     */
    public function bottomedit()
    {
        $model = new SettingModel;
        $data = $this->postData();
        if ($model->edit('nav', $data)) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }
}
